<template>
  <div class="app-container">
    <!-- 顶部搜索区域 -->
    <div class="filter-container">
      <div class="search-container">
        <div class="search-item">
          <span class="search-title">器材名称</span>
          <el-input size="small" v-model="name" placeholder="请输入器材名称" style="width: 220px"></el-input>
        </div>
        <div class="search-item">
          <span class="search-title">器材类型</span>
          <el-select size="small" v-model="type" placeholder="请选择器材类型" style="width: 150px">
            <el-option label="全部" value=""></el-option>
            <el-option label="有氧器械" value="有氧器械"></el-option>
            <el-option label="力量器械" value="力量器械"></el-option>
            <el-option label="功能性器械" value="功能性器械"></el-option>
          </el-select>
        </div>
        <div class="search-item">
          <span class="search-title">状态</span>
          <el-select size="small" v-model="status" placeholder="请选择状态" style="width: 120px">
            <el-option label="全部" value=""></el-option>
            <el-option label="正常" :value="1"></el-option>
            <el-option label="维修中" :value="2"></el-option>
            <el-option label="报废" :value="3"></el-option>
          </el-select>
        </div>
        <div class="search-item">
          <el-button type="primary" size="small" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </div>
      </div>
      <div class="right-container">
        <el-button type="primary" plain icon="el-icon-plus" size="small" @click="handleAdd">新增器材</el-button>
      </div>
    </div>

    <!-- 数据区域 -->
    <el-table :data="equipments" style="width: 100%;" height="700">
      <el-table-column prop="equipmentId" align="center" label="器材ID" width="100"></el-table-column>
      <el-table-column prop="name" align="center" label="器材名称"></el-table-column>
      <el-table-column prop="type" align="center" label="器材类型"></el-table-column>
      <el-table-column prop="brand" align="center" label="品牌"></el-table-column>
      <el-table-column prop="model" align="center" label="型号"></el-table-column>
      <el-table-column prop="location" align="center" label="位置"></el-table-column>
      <el-table-column prop="purchaseDate" align="center" label="购买日期" width="120"></el-table-column>
      <el-table-column prop="price" align="center" label="价格(元)" width="100">
        <template slot-scope="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : (scope.row.status === 2 ? 'warning' : 'danger')">
            {{ scope.row.status === 1 ? '正常' : (scope.row.status === 2 ? '维修中' : '报废') }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createdTime" label="创建时间" align="center" width="160"></el-table-column>
      <el-table-column label="操作" width="280" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.row)">
            <i class="el-icon-edit" style="margin-right: -3px;"></i>
            编辑
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleStatusChange(scope.row)"
          >
            <i class="el-icon-refresh" style="margin-right: -3px;"></i>
            状态
          </el-button>
          <el-button
            size="mini"
            type="text"
            style="margin-right: 4px;"
            @click="handleDelete(scope.row)"
          >
            <i class="el-icon-delete" style="margin-right: -3px;"></i>
            删除
          </el-button>
          <el-dropdown size="mini">
            <el-button size="small" type="text">
              <i class="el-icon-d-arrow-right" style="margin-right: -5px;"></i>
              更多
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item icon="el-icon-view" @click.native="handleViewDetail(scope.row)">查看详情</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
      class="pagination-container"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    ></el-pagination>

    <!-- 添加/编辑器材对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :before-close="handleClose"
    >
      <el-form
        :model="formData"
        class="addDialog"
        :rules="rules"
        ref="formRef"
        size="small"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="器材名称" prop="name">
              <el-input v-model="formData.name"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="器材类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择器材类型" style="width: 100%">
                <el-option label="有氧器械" value="有氧器械"></el-option>
                <el-option label="力量器械" value="力量器械"></el-option>
                <el-option label="功能性器械" value="功能性器械"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="formData.brand"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="formData.model"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="购买日期" prop="purchaseDate">
              <el-date-picker
                v-model="formData.purchaseDate"
                type="date"
                placeholder="选择日期"
                format="yyyy-MM-dd"
                value-format="yyyy-MM-dd"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="formData.price" :min="0" :precision="2" style="width: 100%"></el-input-number>
              <span style="margin-left: 10px; color: #999;">元</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="位置" prop="location">
          <el-input v-model="formData.location"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 状态修改对话框 -->
    <el-dialog title="修改器材状态" :visible.sync="statusDialogVisible" width="400px">
      <el-form :model="statusForm" label-width="100px">
        <el-form-item label="器材名称">
          <span>{{ statusForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前状态">
          <el-tag :type="statusForm.status === 1 ? 'success' : (statusForm.status === 2 ? 'warning' : 'danger')">
            {{ statusForm.status === 1 ? '正常' : (statusForm.status === 2 ? '维修中' : '报废') }}
          </el-tag>
        </el-form-item>
        <el-form-item label="新状态">
          <el-radio-group v-model="statusForm.newStatus">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="2">维修中</el-radio>
            <el-radio :label="3">报废</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="statusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirmStatusChange">确认修改</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog title="确认删除" :visible.sync="deleteDialogVisible" width="300px">
      <template #content>
        <p>确定要删除器材 {{ deleteEquipmentName }} 吗？</p>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="handleConfirmDelete">确认删除</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { queryEquipments, saveEquipment, deleteEquipment, updateEquipmentStatus } from "@/api/equipment";

export default {
  data() {
    return {
      // 器材数据
      equipments: [],

      // 搜索筛选
      name: "",
      type: "",
      status: "",

      // 分页
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 对话框
      dialogVisible: false,
      dialogType: "add", // 'add' 或 'edit'
      dialogTitle: "添加器材",
      formData: {
        name: "", // 器材名称
        type: "", // 器材类型
        brand: "", // 品牌
        model: "", // 型号
        purchaseDate: "", // 购买日期
        price: 0, // 价格
        location: "" // 位置
      },

      // 表单验证规则
      rules: {
        name: [{ required: true, message: "请输入器材名称", trigger: "blur" }],
        type: [{ required: true, message: "请选择器材类型", trigger: "change" }],
        brand: [{ required: true, message: "请输入品牌", trigger: "blur" }],
        model: [{ required: true, message: "请输入型号", trigger: "blur" }],
        purchaseDate: [{ required: true, message: "请选择购买日期", trigger: "change" }],
        price: [{ required: true, message: "请输入价格", trigger: "blur" }],
        location: [{ required: true, message: "请输入位置", trigger: "blur" }]
      },

      // 状态修改相关
      statusDialogVisible: false,
      statusForm: {
        equipmentId: "",
        name: "",
        status: 1,
        newStatus: 1
      },

      // 删除相关
      deleteDialogVisible: false,
      deleteEquipmentId: "",
      deleteEquipmentName: "",
    };
  },

  methods: {
    // 分页
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.handleSearch();
    },

    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.handleSearch();
    },

    // 搜索
    handleSearch() {
      const params = {
        name: this.name,
        type: this.type,
        status: this.status,
        pageSize: this.pageSize,
        page: this.currentPage
      };

      // 调用实际的API
      queryEquipments(params).then(res => {
        if (res.data.code === 1) {
          const data = res.data.data;
          this.equipments = data.records || [];
          this.total = data.total || 0;
        } else {
          this.$message.error(res.data.msg || "查询失败");
          // 如果API失败，使用模拟数据
          this.equipments = [
            {
              equipmentId: 1,
              name: "跑步机",
              type: "有氧器械",
              brand: "美国品牌",
              model: "TM-2000",
              location: "有氧区A1",
              purchaseDate: "2024-01-01",
              price: 15000.00,
              status: 1,
              createdTime: "2025-06-01 10:00:00"
            },
            {
              equipmentId: 2,
              name: "哑铃组",
              type: "力量器械",
              brand: "国产品牌",
              model: "DB-SET-50",
              location: "力量区B1",
              purchaseDate: "2024-01-01",
              price: 3000.00,
              status: 1,
              createdTime: "2025-06-02 14:30:00"
            },
            {
              equipmentId: 3,
              name: "动感单车",
              type: "有氧器械",
              brand: "欧洲品牌",
              model: "SC-PRO",
              location: "有氧区A2",
              purchaseDate: "2024-01-01",
              price: 8000.00,
              status: 2,
              createdTime: "2025-06-03 09:00:00"
            }
          ];
          this.total = 3;
        }
      }).catch(error => {
        console.error("查询器材失败:", error);
        this.$message.error("网络错误，查询失败");
        // 网络错误时使用模拟数据
        this.equipments = [
          {
            equipmentId: 1,
            name: "跑步机",
            type: "有氧器械",
            brand: "美国品牌",
            model: "TM-2000",
            location: "有氧区A1",
            purchaseDate: "2024-01-01",
            price: 15000.00,
            status: 1,
            createdTime: "2025-06-01 10:00:00"
          }
        ];
        this.total = 1;
      });
    },

    // 添加器材
    handleAdd() {
      this.dialogType = "add";
      this.dialogTitle = "添加器材";
      this.formData = {
        name: "",
        type: "",
        brand: "",
        model: "",
        purchaseDate: "",
        price: 0,
        location: ""
      };
      this.dialogVisible = true;
    },

    // 编辑器材
    handleEdit(row) {
      this.dialogType = "edit";
      this.dialogTitle = "编辑器材";
      this.formData = { ...row };
      this.dialogVisible = true;
    },

    // 保存器材信息
    handleSave() {
      this.$refs.formRef.validate(valid => {
        if (valid) {
          if (this.dialogType === "add") {
            // 添加新器材
            console.log("添加器材:", this.formData);
            saveEquipment(this.formData).then(res => {
              if (res.data.code === 1) {
                this.$message.success("添加成功");
                this.dialogVisible = false;
                this.handleSearch();
              } else {
                this.$message.error(res.data.msg || "添加失败");
              }
            }).catch(error => {
              console.error("添加器材失败:", error);
              this.$message.error("网络错误，添加失败");
            });
          } else {
            // 编辑器材
            console.log("编辑器材:", this.formData);
            this.$message.success("修改成功");
            this.dialogVisible = false;
            this.handleSearch();
          }
        } else {
          this.$message.error("请完善表单信息");
          return false;
        }
      });
    },

    // 关闭对话框
    handleClose(done) {
      this.$refs.formRef.resetFields();
      done();
    },

    // 修改器材状态
    handleStatusChange(row) {
      this.statusForm = {
        equipmentId: row.equipmentId,
        name: row.name,
        status: row.status,
        newStatus: row.status
      };
      this.statusDialogVisible = true;
    },

    // 确认状态修改
    handleConfirmStatusChange() {
      if (this.statusForm.status === this.statusForm.newStatus) {
        this.$message.warning("状态未发生变化");
        return;
      }

      console.log("修改器材状态:", this.statusForm);
      updateEquipmentStatus(this.statusForm.equipmentId, this.statusForm.newStatus).then(res => {
        if (res.data.code === 1) {
          this.$message.success("状态修改成功");
          this.statusDialogVisible = false;
          this.handleSearch();
        } else {
          this.$message.error(res.data.msg || "状态修改失败");
        }
      }).catch(error => {
        console.error("修改器材状态失败:", error);
        this.$message.error("网络错误，状态修改失败");
      });
    },

    // 删除器材
    handleDelete(row) {
      this.deleteEquipmentId = row.equipmentId;
      this.deleteEquipmentName = row.name;
      this.deleteDialogVisible = true;
    },

    // 确认删除
    handleConfirmDelete() {
      console.log("删除器材:", this.deleteEquipmentId);
      deleteEquipment(this.deleteEquipmentId).then(res => {
        if (res.data.code === 1) {
          this.$message.success("删除成功");
          this.deleteDialogVisible = false;
          this.handleSearch();
        } else {
          this.$message.error(res.data.msg || "删除失败");
        }
      }).catch(error => {
        console.error("删除器材失败:", error);
        this.$message.error("网络错误，删除失败");
      });
    },

    // 查看器材详情
    handleViewDetail(row) {
      this.$alert(`
        <div style="text-align: left;">
          <p><strong>器材名称：</strong>${row.name}</p>
          <p><strong>器材类型：</strong>${row.type}</p>
          <p><strong>品牌：</strong>${row.brand}</p>
          <p><strong>型号：</strong>${row.model}</p>
          <p><strong>购买日期：</strong>${row.purchaseDate}</p>
          <p><strong>价格：</strong>¥${row.price}</p>
          <p><strong>位置：</strong>${row.location}</p>
          <p><strong>状态：</strong>${row.status === 1 ? '正常' : (row.status === 2 ? '维修中' : '报废')}</p>
          <p><strong>创建时间：</strong>${row.createdTime}</p>
        </div>
      `, '器材详情', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true
      });
    },
  },

  mounted() {
    this.handleSearch();
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-title {
  font-size: 14px;
  color: #606266;
  white-space: nowrap;
}

.right-container {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.addDialog {
  padding: 20px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-table th {
  background-color: #f5f7fa;
}

.el-tag {
  font-size: 12px;
}

.el-button--text {
  padding: 0;
  margin-right: 8px;
}

.el-dropdown {
  margin-left: 8px;
}
</style>
